import hcpUtils from '@/utils/hcpUtils';
import {getIcons, nodeColors, fittingString, uuid} from '@/modules/topology/utils';
import { queryAZ, queryHosts, queryServer, getHostAlarm, getServerAlarm } from './dataSource';

export const getModule = (moduleData) => {
    let serverModule = null;
    let phyServerModule = null;

    // hcpUtils.treeDataIteration(moduleData, function(item) {
    //     item.children = item.children ? item.children.concat(item.definitions||[]) : item.definitions||[];
    //     if(item.moduleCode == "server") {
    //         serverModule = item;
    //     }
    //     if(item.moduleCode == "phy_server") {
    //         phyServerModule = item;
    //     }
    // })

    return {serverModule: {
        "id": "4",
        "cmModuleId": "557fe7f3-9b1e-440f-b271-8c87dfa02540",
        "moduleName": "云主机",
        "moduleClassificationId": "3",
        "moduleCode": "server",
        "moduleTable": "resource_data",
        "moduleIcon": "icon-yunquyu",
    } , phyServerModule:{
        "id": "46",
        "cmModuleId": "e782ddd6-7e22-4982-b340-74a9d9120cdc",
        "moduleName": "服务器",
        "moduleClassificationId": "45",
        "moduleCode": "phy_server",
        "moduleTable": "resource_data",
        "moduleIcon": "icon-fuwuqi",
    }};
}

const formatAz = (data, allHost) => {
    if(!data?.length) return [];
    return data.map(az => {
        az._id = az.id;
        az.id = az.uuid;
        az.label = az.azName; 
        az.icon = getIcons('icon-yunquyu');
        const hosts = allHost.filter(hs => hs.azUuid == az.uuid);
        az.children = hosts;
        return az;
    });
}

const formatHost = (data, phyServerModule, alarmHosts) => {
    if(!data?.length) return [];
    return data.map(item => {
        item._id = item.id;
        item.id = item.uuid;
        item.label = item.facilityName;
        item.graphType = "phy_server";
        item.monitorType = "ecs";
        item.hostType = item.type;
        item.type = "center-node";
        item.icon = getIcons(phyServerModule.moduleIcon || 'icon-yunquyu');
        item.module = phyServerModule;
        if(alarmHosts[item.facilityName]) {
            item.showAlarm = true;
            item.alarmInfo = alarmHosts[item.facilityName];
        }
        return item;
    })
}

const formatServer = (data, serverModule, alarmServer) => {
    if(!data?.length) return [];
    return data.map(item => {
        item.id = item.cm_unid + "_" + item.uuid;
        item.label = item.cm_name;
        item.graphType = "server";
        item.monitorType = "ecs";
        item.icon = getIcons(serverModule.moduleIcon || 'icon-yunquyu');
        item.module = serverModule;
        if(alarmServer[item.uuid]) {
            item.showAlarm = true;
            item.alarmInfo = alarmServer[item.uuid];
        }
        return item;
    })
}

export function addNodeServer (firstHost, serverModule, fn) {
    queryServer({
        module: serverModule,
        az_code: firstHost.azCode, 
        region_id: firstHost.regionId,
        host_name: firstHost.facilityName
    }).then((res) => {
        if(!res?.length) {
            if(fn) fn(res)
            return; 
        }
        const resourceUuids = res.filter(item => item.uuid != null).map(item => item.uuid);
        getServerAlarm(resourceUuids)
          .then((alarmServer) => {
            const servers = formatServer(res, serverModule, alarmServer)
            if(fn) fn(servers, alarmServer)
          })
    })
}

/**
 * 
 * @param {*} 
 * 1、查询可用域
 *    查询宿主机的告警数据（全量）
 *    查询宿主机（全量）
 * 2、根据第一个宿主机，查询云主机
 *    获取所有云主机的uuid，查询云主机的告警数据
 */
export async function getGraphData ({region, moduleData, setGraphLoading, setGraphData}) {
    setGraphLoading(true);
    const {serverModule , phyServerModule} = getModule(moduleData);
    let graphData = Object.assign({},region, {icon: getIcons('icon-yunquyu'), label: region.regionName});

    const fn = [queryAZ(region.id), getHostAlarm(), queryHosts()];
    await Promise.all(fn).then(async(res) => {
        const alarmHosts = res[1];
        const allHost = formatHost(res[2], phyServerModule, alarmHosts);
        const allAz = formatAz(res[0], allHost);
        graphData.children = allAz;
        if(graphData.children?.[0]?.children?.[0]) {
            addNodeServer(graphData.children[0].children[0], serverModule, (servers)=> {
                if(servers && servers.length) {
                    graphData.children[0].children[0].children = servers;
                }
                setGraphData(graphData);
                setGraphLoading(false);
            })
        } else {
            setGraphData(graphData);
            setGraphLoading(false);
        }
    })
}